package com.wlj.service.impl;

import com.google.common.collect.Lists;
import com.wlj.dao.MenuDao;
import com.wlj.dto.MenuDTO;
import com.wlj.pojo.TbMenu;
import com.wlj.service.MenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;
    
    @Override
    public List<MenuDTO> getAllMenus() {
        List<TbMenu> rootMenus = menuDao.getRootMenus();
        return getMenusTree(rootMenus);
    }

    private List<MenuDTO> getMenusTree(List<TbMenu> menus){
        List<MenuDTO> menuDTOS = Lists.newArrayList();
        if(menus.isEmpty()){
            return menuDTOS;
        }
        for (TbMenu menu : menus) {
            MenuDTO menuDTO = new MenuDTO();
            BeanUtils.copyProperties(menu,menuDTO);
            List<TbMenu> chils = menuDao.getMenusByParentId(menuDTO.getId());
            if(chils.size()!=0){
                menuDTO.setChilds(getMenusTree(chils));
                menuDTO.setHasChild(true);
            }else{
                menuDTO.setHasChild(false);
            }
            menuDTOS.add(menuDTO);
        }
        return menuDTOS;
    }
}
